﻿using System;
using Db4objects.Db4o.Config;
using Db4objects.Db4o;
using Db4objects.Db4o.Query;
using System.IO;
using BikeSystem.Models;

namespace BikeSystem.DAL
{
    public static class CommonUtilService
    {
        readonly static string YapFileName = Path.Combine(Environment.CurrentDirectory, "bikesystem.yap");

        public static string genrateNextSerialNumber(string profix) {

            return genrateNextSerialNumber(null, profix);
        }
        public static string genrateNextSerialNumber(IObjectContainer db, string profix)
        {

            string NextSerialNumber = profix.ToUpper().PadRight(2,'0');

            //yyyyMMddHHmmss
            NextSerialNumber += System.DateTime.Now.ToString("yyyyMMddHH");

            if (null == db)
            {
                using (db = Db4oEmbedded.OpenFile(YapFileName))
                {
                    NextSerialNumber += gentrateNextSerial(db).PadLeft(10, '0');
                }
            }
            else
            {
                NextSerialNumber += gentrateNextSerial(db).PadLeft(10, '0');
            }

            return NextSerialNumber;
        }

        private static string gentrateNextSerial(IObjectContainer db)
        {

            long nextsn = 1;
            string optionCode = "SN" + "1".PadLeft(20,'0');


            SystemOption qsop = new SystemOption();
            qsop.OptionCode = optionCode;
            qsop.OptionType = "SYSTEM_NEXT_SERIALNUMBER";

            IObjectSet result = db.QueryByExample(qsop);
            if (result.HasNext())
            {
                SystemOption sop = (SystemOption)result.Next();
                long serialno = long.Parse(sop.OptionValue);
                if (serialno.ToString().Length > 10)
                {
                    serialno = 0;
                }
                nextsn = serialno + 1;
                sop.OptionValue = nextsn.ToString();
                db.Store(sop);
            }
            else
            {
                SystemOption sop = new SystemOption();
                sop.OptionCode = optionCode;
                sop.OptionName = "SYSTEM_NEXT_SERIALNUMBER";
                sop.OptionType = "SYSTEM_NEXT_SERIALNUMBER";
                sop.OptionValue = nextsn.ToString();
                sop.OptionOrder = 0;
                db.Store(sop);
            }

            db.Commit();
            return nextsn.ToString();
        }

    }
}
